package com.zhongwang.mms.module.buy.controller;

import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.module.buy.model.BPreOrderPlan;
import com.zhongwang.mms.module.buy.service.BuyPreOrderPlanCheckService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.FileUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;


/**
 * 预购计划审核接口层
 */
@Controller
@RequestMapping("/buy/preOrderPlanCheck")
public class BuyPreOrderPlanCheckController extends BaseController {
    @Autowired
    private BuyPreOrderPlanCheckService buyPreOrderPlanCheckService;
    @Autowired
    private LogService logService;
    /**
     * 上传文件路径
     */
    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * 跳转到预购计划审核页面
     * @param model
     * @return
     */
    @GetMapping("/page")
    public String page(Model model) {
        return "/buy/preOrderPlan/check/page";
    }

    /**
     * 查询已经提交的预购计划列表
     * @param where
     * @return
     */
    @ResponseBody
    @PostMapping("/list")
    @RequiresPermissions(value = {"buy:preorderplancheck:view"}, logical = Logical.OR)
    public JsonResult list(BPreOrderPlan where) {
        startPage();
        List<BPreOrderPlan> list = buyPreOrderPlanCheckService.findBPreOrderPlanByQuery(where);
        return jsonResult(list);
    }

    /**
     * 根据预购编号code查询预购计划列表
     * @param code 预购编号
     * @return 预购计划列表
     */
    @ResponseBody
    @PostMapping("/getProOrderPlanListByCode")
    @RequiresPermissions(value = {"buy:preorderplancheck:check"}, logical = Logical.OR)
    public JsonResult getProOrderPlanListByCode(String code) {
        List<BPreOrderPlan> list = buyPreOrderPlanCheckService.findBPreOrderPlanByCode(code);
        return success().setData(list);
    }

    /**
     * 根据预购计划ID判断附件文件是否存在
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/getAttachmentIsExist")
    @RequiresPermissions(value = {"buy:preorderplancheck:download"}, logical = Logical.OR)
    public JsonResult getAttachmentIsExist(Integer id) {
        BPreOrderPlan preOrderPlan = buyPreOrderPlanCheckService.getBPreOrderPlanByPrimaryKey(id);
        String attachmentUrl = preOrderPlan.getAttachment();
        String msg = "有文件";
        if(attachmentUrl == null || attachmentUrl.equals("")){
            msg = "没有文件";
        }else{
            attachmentUrl = attachmentUrl.replace("/files/", "/");
            String localPath = uploadPath + attachmentUrl.substring(attachmentUrl.indexOf("/"));
            if(new File(localPath).exists()) {
                return success(msg);
            }
        }
        return error(msg);
    }

    /**
     * 根据预购计划ID下载附件
     * @param id 预购计划ID
     */
    @GetMapping("/downloadAttachment/{id}")
    @RequiresPermissions(value = {"buy:preorderplancheck:download"}, logical = Logical.OR)
    public ResponseEntity<Resource> downloadAttachment(@PathVariable("id") Integer id,
                                                       HttpServletResponse httpServletResponse,
                                                       HttpServletRequest request) throws MalformedURLException {
        BPreOrderPlan preOrderPlan = buyPreOrderPlanCheckService.getBPreOrderPlanByPrimaryKey(id);
        String attachmentUrl = preOrderPlan.getAttachment();
        attachmentUrl = attachmentUrl.replace("/files/", "/");
        String localPath = uploadPath + attachmentUrl.substring(attachmentUrl.indexOf("/"));
        Path realPath = Paths.get(localPath); // 真实文件
        Resource resource = new UrlResource(realPath.toUri());
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }else{
            // 根据浏览器类型决定编码方式
            String agent = request.getHeader("User-Agent");
            String disposition = "attachment; filename*=UTF-8''" + UriUtils.encode(preOrderPlan.getAttachmentName(), StandardCharsets.UTF_8);
            logService.saveLog("采购管理-预购计划审核", "下载预购主题为：" + preOrderPlan.getName() + "，预购编码为：" + preOrderPlan.getCode() + ",物料跟踪码为：" + preOrderPlan.getTrackNumber() + ",物料描述为：" + preOrderPlan.getMaterialDesc() + "的名称为：" + preOrderPlan.getAttachmentName() + "的附件（附件大小：" + FileUtils.formatFileSize(realPath.toFile().length()) + "）！");
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, disposition)
                    .body(resource);
        }
    }

    /**
     * 审核计划
     * @param codes 审批通过的预购编号
     * */
    @ResponseBody
    @PostMapping("/success")
    @RequiresPermissions({"buy:preorderplancheck:check"})
    public JsonResult success(@RequestParam("codes") List<String> codes) {
        return jsonResult(buyPreOrderPlanCheckService.verify(codes));
    }

    /**
     * 驳回计划
     * @param codes 驳回的预购编号
     * @param rejectReason 驳回原因
     * */
    @ResponseBody
    @PostMapping("/reject")
    @RequiresPermissions({"buy:preorderplancheck:check"})
    public JsonResult reject(@RequestParam("codes") List<String> codes,String rejectReason) {
        return jsonResult(buyPreOrderPlanCheckService.reject(codes,rejectReason));
    }
}
